package com.hongkuncheng.cms.controller.index;

import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.hibernate.LockMode;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.controller.BaseController;
import com.hongkuncheng.cms.helper.CookieHelper;
import com.hongkuncheng.cms.helper.PageHelper;
import com.hongkuncheng.cms.model.VoteOption;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@Transactional
@RequestMapping("vote")
@ResponseBody
public class IvoteController extends BaseController {

    @RequestMapping("getpoll")
    public void getpoll() {
        List<VoteOption> voteoptions = factorySession.createCriteria(VoteOption.class).list();
        JSONArray array = new JSONArray();
        for (VoteOption voteoption : voteoptions) {
            JSONObject object = new JSONObject();
            object.put("id", voteoption.getId());
            object.put("poll", voteoption.getPoll());
            array.add(object);
        }
        print(array);
    }

    @RequestMapping("submit")
    public void submit() {
        String url = request.getParameter("callbackurl");
        String msg = null;
        if (CookieHelper.GetCookie(request, "vote", false) == null) {
            int voteoptionId = Integer.parseInt(request.getParameter("voteoptionid"));
            VoteOption voteoption = factorySession.load(VoteOption.class, voteoptionId, LockMode.PESSIMISTIC_WRITE);
            voteoption.setPoll(voteoption.getPoll() + 1);
            msg = "投票成功";
            CookieHelper.SetCookie(response, "vote", "1", false);
        } else {
            msg = "您已投票，暂时不允许重复投票，请您稍后再试";
        }
        PageHelper.alertAndRedirect(msg, url);
    }

}
